package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/ulrichSchreiner/go-icap"
)

var ISTag = "\"ICAP SERVER\""

func main() {
	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}

	http.Handle("/", http.FileServer(http.Dir(dir+"/sites")))

	icap.HandleFunc("/receive", recvHandle)
	icap.ListenAndServe(":11344", nil)
}

func recvHandle(w icap.ResponseWriter, req *icap.Request) {
	h := w.Header()
	h.Set("ISTag", ISTag)
	h.Set("Service", "ICAP Filter")

	switch req.Method {
	case "OPTIONS":
		h.Set("Methods", "REQMOD")
		h.Set("Allow", "204")
		w.WriteHeader(200, nil, false)
	case "REQMOD":

		switch req.Request.Host {
		case "gateway":
			// 启动本地服务，通过静态文件服务
			icap.ServeLocally(w, req)
		case "book.weigou365.cn":

			req.Request.Host = "forum.weigou365.cn"
			req.Request.URL.Host = "formum.weigou365.cn"
			w.WriteHeader(200, req.Request, false)
		default:
			// 未做任何修改，继续操作
			w.WriteHeader(204, nil, false)
		}
	default:
		w.WriteHeader(405, nil, false)
		fmt.Println("Invalid request method")
	}
}
